package com.suixun.controller.base;

import com.suixun.controller.vo.OfficialVo;
import com.suixun.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suixun.enums.ApiCode;
import com.suixun.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.ui.Model;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 功能描述:  基础控制器
 *
 * @author jacky
 * @date 2018年1月6日上午10:37:42
 */
public class BaseController {

    protected final static Logger logger = LoggerFactory.getLogger(BaseController.class);

    protected Result success(Object obj) {
        Result res = new Result();
        res.setData(obj);
        return res;
    }

    protected Result success() {
        Result res = new Result();
        res.setData(null);
        return res;
    }

    protected Result fail(Exception e, int code) {
        Result res = new Result();
        res.setCode(code);
        res.setMsg(e);
        return res;
    }

    protected Result fail(Exception e) {
        Result res = new Result();
        res.setCode(ApiCode.HTTP_500.getCode());
        res.setMsg(e);
        return res;
    }

    protected Result fail(String msg) {
        Result res = new Result();
        res.setCode(ApiCode.HTTP_500.getCode());
        res.setMsg(msg);
        return res;
    }

    protected void loggerDebug(String msg, Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug(msg, e);
        }
    }

    protected void loggerInfo(String msg, Exception e) {
        if (logger.isInfoEnabled()) {
            logger.debug(msg, e);
        }
    }

    protected void loggerError(String msg, Exception e) {
        if (logger.isErrorEnabled()) {
            logger.debug(msg, e);
        }
    }

    protected <M extends com.baomidou.mybatisplus.activerecord.Model> void get(OfficialVo officialVo, com.baomidou.mybatisplus.activerecord.Model<M> mModel, Model model) throws UnsupportedEncodingException {
        BeanUtils.copyProperties(mModel, officialVo);
        Integer createDate = DateUtil.getDate(officialVo.getCreateTime());
        String createMonth = DateUtil.getEnglishMonth(officialVo.getCreateTime());
        officialVo.setCreateDate(createDate);
        officialVo.setCreateMonth(createMonth);
        if (StringUtils.isNotBlank(officialVo.getContent())) {
            officialVo.setContent(URLDecoder.decode(officialVo.getContent(), "UTF-8"));
        }
        model.addAttribute("commonBean", officialVo);
    }

}
